package com.ugold.web.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ugold.web.common.Result;
import com.ugold.web.common.SnowflakeIdWorker;
import com.ugold.web.common.exception.BizException;
import com.ugold.web.common.exception.ErrorEnum;

import lombok.extern.slf4j.Slf4j;

/**
 * 上传图片
 * 
 * @author dingjian
 * @date 2019/04/19 11:47:25
 */
@Slf4j
@Controller
@RequestMapping(method = RequestMethod.POST)
public class UploadController {

	/**
	 * 图片上传凭证
	 */
	@Value("${images.upload.access.token}")
	private String accessToken;

	/**
	 * 图片上传路径
	 */
	@Value("${images.upload.directory}")
	private String uploadDirectory;

	/**
	 * 互联网ROOT_URL
	 */
	@Value("${images.internet.url.root}")
	private String internetUrlRoot;

	// ID生成工具
	private SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(0, 0);



	/**
	 * A07.上传图片
	 * 
	 * @author dingjian
	 * @date 2019/04/19 10:04:35
	 * @param req
	 * @return
	 */
	@RequestMapping(value = "/images")
	@ResponseBody
	public Result<?> uploadImagesFile(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
		String accessToken = request.getParameter("accessToken");
		if (!StringUtils.equals(this.accessToken, accessToken)) {
			throw new BizException(ErrorEnum.ERROR_NO_AUTHORITY);
		}
		if (files == null || files.length == 0) {
			throw new BizException(ErrorEnum.ERROR_PARAM, "至少需要上传1张图片");
		}
		checkData(files);
		List<String> imagesUrl = saveImages(files, StringUtils.EMPTY);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("imagesUrl", imagesUrl);
		Result<Map<String, Object>> buildSuccessResult = Result.buildSuccessResult(map);
		return buildSuccessResult;
	}

	/**
	 * 检查图片格式
	 * 
	 * @author dingjian
	 * @date 2019年7月23日下午3:43:21
	 * @param files
	 */
	private void checkData(MultipartFile[] files) {
		if (files != null) {
			try {
				for (MultipartFile multipartFile : files) {
					double length = multipartFile.getBytes().length / 1024d / 1024d;
					if (length > 16.0) {
						throw new BizException(ErrorEnum.ERROR_PARAM, "上传的单个文件不能超过16MB");
					}
					log.info("ContentType={}", multipartFile.getContentType());
					if (StringUtils.startsWith(multipartFile.getContentType(), MediaType.IMAGE_JPEG_VALUE)
							|| StringUtils.startsWith(multipartFile.getContentType(), MediaType.IMAGE_PNG_VALUE)) {
						// 图片格式正确
						continue;
					} else {
						throw new BizException(ErrorEnum.ERROR_PARAM, "上传文件需要为图片格式");
					}
				}
			} catch (IOException e) {
				log.error("检查文件大小异常，异常信息:" + e.getMessage(), e);
				throw new BizException(ErrorEnum.ERROR_PARAM, "上传文件失败");
			}
		}
	}

	/**
	 * 保存图片
	 * 
	 * @author dingjian
	 * @date 2019年7月23日下午3:44:00
	 * @param files           需要保存的图片文件
	 * @param uploadDirectory 给予根路径的子目录，为空则保存与根目录
	 * @return
	 */
	private List<String> saveImages(MultipartFile[] files, String extDirectory) {
		List<String> imagesURL = new ArrayList<String>(2);
		if (files == null) {
			return imagesURL;
		}
		// 真实保存路径
		String realSaveDir = uploadDirectory;
		if (!StringUtils.isBlank(extDirectory)) {
			realSaveDir = uploadDirectory + "/" + extDirectory;
		}
		File fileDir = new File(realSaveDir);
		// 检查路径是否存在
		if (!fileDir.exists()) {
			log.error("保存图片的路径不存在，路径={}", realSaveDir);
			throw new BizException(ErrorEnum.ERROR_SERVICE.getErrorCode(), "文件目录不存在");
		}
		for (MultipartFile multipartFile : files) {
			// 定义文件名
			String fileName = String.valueOf(snowflakeIdWorker.nextId()) + "."
					+ StringUtils.substringAfter(multipartFile.getContentType(), "/");
			if (StringUtils.isBlank(extDirectory)) {
				imagesURL.add(this.internetUrlRoot + "/" + fileName);
			} else {
				imagesURL.add(this.internetUrlRoot + "/powisewealthImages/" + fileName);
			}

			File imageFile = Paths.get(realSaveDir, fileName).toAbsolutePath().toFile();
			try (FileOutputStream fos = new FileOutputStream(imageFile);) {
				IOUtils.copy(multipartFile.getInputStream(), fos);
			} catch (IOException e) {
				log.error("保存图片异常，异常信息：" + e.getLocalizedMessage(), e);
				throw new BizException(e.getLocalizedMessage());
			}
		}
		return imagesURL;
	}
}
